"""
统一响应格式处理工具
"""

from datetime import datetime
from typing import Sequence, TypeVar

from app.schemas.response import APIResponse, PaginatedResponse

T = TypeVar("T")


def _current_timestamp() -> str:
    """生成统一的UTC时间戳"""
    return datetime.utcnow().isoformat() + "Z"


def success_response(data: T | None = None, message: str = "success", code: int = 200) -> APIResponse[T]:
    """成功响应，直接返回Pydantic模型以便FastAPI文档识别"""
    return APIResponse[T](
        code=code,
        message=message,
        data=data,
        timestamp=_current_timestamp(),
    )


def error_response(message: str = "Internal Server Error", code: int = 500) -> APIResponse[None]:
    """错误响应"""
    return APIResponse[None](
        code=code,
        message=message,
        data=None,
        timestamp=_current_timestamp(),
    )


def paginated_response(
    items: Sequence[T],
    total: int,
    page: int,
    size: int,
    message: str = "success",
) -> APIResponse[PaginatedResponse[T]]:
    """分页响应"""
    pagination = PaginatedResponse[T](
        items=list(items),
        total=total,
        page=page,
        size=size,
    )
    return success_response(data=pagination, message=message)
